package com.itgacl.magic4j.modules.comm.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itgacl.magic4j.common.bean.PageData;
import com.itgacl.magic4j.common.bean.PageParam;
import com.itgacl.magic4j.common.enums.ErrorCodeEnum;
import com.itgacl.magic4j.common.util.AssertUtil;
import com.itgacl.magic4j.common.validator.DataValidator;
import com.itgacl.magic4j.libcommon.component.license.bean.LicenseInfo;
import com.itgacl.magic4j.libcommon.component.license.dto.LicenseDTO;
import com.itgacl.magic4j.libcommon.component.license.service.LicenseService;
import com.itgacl.magic4j.libcommon.component.storage.StorageFactory;
import com.itgacl.magic4j.libcommon.component.storage.bean.UploadResult;
import com.itgacl.magic4j.libcommon.exception.Magic4jException;
import com.itgacl.magic4j.libcommon.util.DateUtils;
import com.itgacl.magic4j.libcommon.util.FileUtil;
import com.itgacl.magic4j.modules.comm.converter.CommLicenseConverter;
import com.itgacl.magic4j.modules.comm.dto.CommLicenseDTO;
import com.itgacl.magic4j.modules.comm.entity.CommLicense;
import com.itgacl.magic4j.modules.comm.mapper.CommLicenseMapper;
import com.itgacl.magic4j.modules.comm.service.CommLicenseService;
import com.itgacl.magic4j.modules.comm.vo.CommLicenseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Classname CommLicenseServiceImpl
 * @Description CommLicenseService实现类
 * @Author Created by xudp (alias:孤傲苍狼) 290603672@qq.com
 * @Date 2021-12-26
 * @Version 1.0
 */
@Slf4j
@Service
public class CommLicenseServiceImpl extends ServiceImpl<CommLicenseMapper, CommLicense> implements CommLicenseService {

    @Autowired
    private LicenseService licenseService;

    @Override
    public void create(CommLicenseDTO commLicenseDTO) {
        dataValidator.validate(commLicenseDTO);//业务处理校验
        CommLicense commLicense = CommLicenseConverter.build().entity(commLicenseDTO);//DTO转换成Entity
        try {
            LicenseDTO licenseDTO = new LicenseDTO();
            BeanUtils.copyProperties(commLicenseDTO,licenseDTO);
            LicenseInfo licenseInfo = licenseService.create(licenseDTO);
            if(licenseInfo!=null){
                BeanUtils.copyProperties(licenseInfo,commLicense);
                commLicense.setExpiryTime(DateUtils.dateToLocalDateTime(commLicenseDTO.getExpiryTime()));
                commLicense.setLicenseCode(licenseInfo.getMachineCode());
                if(StrUtil.isNotBlank(licenseInfo.getLicenseFilePath())){
                    //上传license证书到文件服务器
                    UploadResult uploadResult = StorageFactory.build().uploadFile(licenseInfo.getLicenseFilePath());
                    if(uploadResult.isUploadSuccess()){
                        commLicense.setLicenseFileUrl(uploadResult.getFileUrl());
                        //删除本地文件
                        FileUtil.delete(licenseInfo.getLicenseFilePath());
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new Magic4jException("License证书生成出错，错误信息：" + e.getMessage());
        }
        save(commLicense);//保存
    }

    @Override
    public void update(CommLicenseDTO commLicenseDTO) {
        dataValidator.validate(commLicenseDTO);//业务处理校验
        CommLicense commLicense = CommLicenseConverter.build().entity(commLicenseDTO);//DTO转换成Entity
        try {
            LicenseDTO licenseDTO = new LicenseDTO();
            BeanUtils.copyProperties(commLicenseDTO,licenseDTO);
            LicenseInfo licenseInfo = licenseService.create(licenseDTO);
            if(licenseInfo!=null){
                BeanUtils.copyProperties(licenseInfo,commLicense);
                commLicense.setExpiryTime(DateUtils.dateToLocalDateTime(commLicenseDTO.getExpiryTime()));
                commLicense.setLicenseCode(licenseInfo.getMachineCode());
                if(StrUtil.isNotBlank(licenseInfo.getLicenseFilePath())){
                    //上传license证书到文件服务器
                    UploadResult uploadResult = StorageFactory.build().uploadFile(licenseInfo.getLicenseFilePath());
                    if(uploadResult.isUploadSuccess()){
                        commLicense.setLicenseFileUrl(uploadResult.getFileUrl());
                        //删除本地文件
                        FileUtil.delete(licenseInfo.getLicenseFilePath());
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new Magic4jException("License证书生成出错，错误信息：" + e.getMessage());
        }
        updateById(commLicense);
    }
 
    @Override
    public void deleteById(Long id) {
        removeById(id);//逻辑删除
    }

    @Override
    public void deleteByIds(List<Long> idList) {
        removeByIds(idList);//逻辑删除
    }

    @Override
    public CommLicenseVo getCommLicenseById(Long id) {
        CommLicense commLicense = getById(id);
        AssertUtil.notNull(ErrorCodeEnum.DATA_NOT_EXIST,commLicense);
        return CommLicenseConverter.build().vo(commLicense);
    }

    @Override
    public void delete(QueryWrapper<CommLicense> queryWrapper) {
        remove(queryWrapper);
    }

    @Override
    public void deleteAll() {
        remove(null);//全部删除(逻辑删除)
    }

    @Override
    public List<CommLicenseVo> getList(QueryWrapper<CommLicense> queryWrapper) {
        List<CommLicense> commLicenseList = list(queryWrapper);
        return CommLicenseConverter.build().listVO(commLicenseList);
    }

    @Override
    public PageData<CommLicenseVo> pageList(Page<CommLicense> page, QueryWrapper<CommLicense> queryWrapper) {
        IPage<CommLicense> pageInfo = page(page,queryWrapper);//mybatisPlus分页查询
        IPage<CommLicenseVo> pageVO = CommLicenseConverter.build().pageVO(pageInfo);
        return PageData.build(pageVO);
    }

    @Override
    public PageData<CommLicenseVo> pageList(PageParam pageParam, QueryWrapper<CommLicense> queryWrapper) {
        Page<CommLicense> page = new Page<>(pageParam.getPageNum(),pageParam.getPageSize());
        return pageList(page,queryWrapper);
    }

    /**
     * 数据校验器
     */
    private DataValidator<CommLicenseDTO> dataValidator = new DataValidator<CommLicenseDTO>(){

        /**
        * 数据合法性校验(非空、数据格式等)
        * @param data
        */
        @Override
        protected void validateData(CommLicenseDTO data) {
            //todo:在这里编写数据校验处理逻辑，如果校验不通过，抛出DataValidationException异常
            // throw new DataValidationException("校验不通过抛出的错误提示消息");
        }

        /**
         * 保存之前进行校验(例如：数据是否已存在校验)
         * @param data
         */
        @Override
        protected void beforeCreate(CommLicenseDTO data) {

        }

        /**
         * 更新之前进行校验(例如：数据是否已存在校验)
         * @param data
         */
        @Override
        protected void beforeUpdate(CommLicenseDTO data) {

        }
    };
}
